package com.example.tmall.config;

import com.example.tmall.ums.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author RIKU
 * @date 2020-07-28 09:57
 * @description //TODO
 * To change this template use File | Settings | File Templates.
 */
@Configuration
@EnableWebSecurity
public class TmallSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http); //默认处理
        http.authorizeRequests()
                .antMatchers("/admin/hello").hasRole("hello")
                //如果是请求/admin/hello直接放行
                .antMatchers("/admin/welcome").hasRole("admin")
                //任何请求都需要处理
                .anyRequest().authenticated()
                .and()
                .formLogin().and()
                .httpBasic();
        //定制请求规则，即授权
//        http.authorizeRequests()
//                .antMatchers("/admin/hello")
//                .permitAll()//如果是请求/admin/hello直接放行
//                .antMatchers("/admin/login").permitAll()
//                .and()
//                .csrf().disable();
    }

    @Autowired
    private UmsAdminService umsAdminService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        //定义认证
        /*
        在Security中，UserDetails用户属性固定要求三个属性
        用户名username
        密码password，默认是要求加密的，如果不想加密，在内容前加上{noop}
        角色roles
         */
//        auth.inMemoryAuthentication()
//                .withUser("admin").password("{noop}admin").roles("admin", "hello")
//        ;
        auth.userDetailsService(umsAdminService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        //BCryptPasswordEncoder：hash加密，对相同的字符串加密后的内容每次都不一样
        return new BCryptPasswordEncoder();
    }
}
